<template>
  <h1>UserDetails</h1>
  <h1 v-text="userData.name"></h1>
  <button type="button" @click="bru">onBeforeRouteUpdate</button>
</template>

<script>
import {reactive, ref} from "vue";
import {onBeforeRouteLeave, onBeforeRouteUpdate, useRouter} from "vue-router";

export default {
  name: "User",
  setup() {

    // 与 beforeRouteLeave 相同，无法访问 `this`
    onBeforeRouteLeave((to, from) => {
      const answer = window.confirm(
          'Do you really want to leave? you have unsaved changes!'
      )
      console.log('onBeforeRouteLeave');
      // 取消导航并停留在同一页面上
      if (!answer) return false
    })

    const userData = ref({
      id: '',
      name: ''
    });
    const users = reactive([
      {
        id: '1',
        name: 'user1'
      },
      {
        id: '2',
        name: 'user2'
      },
      {
        id: '3',
        name: 'user3'
      },
    ]);
    const router = useRouter();
    const bru = function () {
      router.push({
        path: '3'
      });
    };
    // 与 beforeRouteUpdate 相同，无法访问 `this`
    onBeforeRouteUpdate((to, from) => {
      console.log('onBeforeRouteUpdate');
      for (const user of users) {
        if (user.id === to.params.id) {
          userData.value = user;
          break;
        }
      }
    })
    return {
      userData, users, bru
    }
  },
}
</script>

<style scoped>

</style>